package cluster.old;

import java.util.Arrays;
import java.util.Hashtable;

import org.grlea.log.SimpleLogger;

import cluster.Duster;

public class DistLookup {
	private final SimpleLogger log = new SimpleLogger(DistLookup.class);
	float[][] table;
	
	public DistLookup(int numColors){
		initTable(numColors);
	}
	
	private int estimateSize(int numColors){
		int estimate = 0;
		int step = numColors;
		while(step > 0){
			estimate += step;
			step /= Math.round(2);
		}
		estimate *= 1.3f;
		return Math.round(estimate);
		
	}
	public void initTable(int numColors){
		int size = estimateSize(numColors);
		table = new float[size][];
		for (int i = 0; i < table.length; i++) {
			table[i] = new float[size];
			Arrays.fill(table[i], Float.NaN);
			size--;
		}
	}
	public boolean isInRange(int a, int b){
		if(a >= table.length) return false;
		if(b >= table[a].length) return false;
		return true;
	}
	
	public void addDist(Duster d1, Duster d2, float dist){
		addDist(d1.ID, d2.ID, dist);
	}
	public void addDist(int id1, int id2, float dist){
		if(!isInRange(id1, id2)){
			log.error("Indexes " + " " + id1+" "+id2 + " are out of range");
			return;
		}
		table[Math.max(id1, id2)][Math.min(id1, id2)] = dist;
	}
	public float getDist(Duster d1, Duster d2){
		return getDist(d1.ID, d2.ID);
	}
	public float getDist(int id1, int id2){
		if(!isInRange(id1, id2)){
			log.error("Indexes " + " " + id1+" "+id2 + " are out of range");
			return Float.NaN;
		}
		float val =  table[Math.max(id1, id2)][Math.min(id1, id2)];
		if(Float.isNaN(val)) return val;
		return val;
	}
	
	public String toString(){
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < table.length; i++){
			for(int j = 0; j < table[i].length; j++)
				sb.append(table[i][j] + ", ");
			
		}
		return sb.toString();
	}

}
